import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '@shared/directives/verification/forbiddenNameValidator';
import { LoginHttpService } from '@app/core/services/http/login/login.http.service';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { UserService } from '@core/services/common/user.service';
import { LoginInOutService } from '@core/services/common/login-in-out.service';
import { Router } from '@angular/router';
import { Store, select } from '@ngrx/store';
import { ActionCode } from '@config/actionCode';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { increment5, increment, decrement, reset, TestSelectors } from '@app/core/services/store/modules/test';
import { StoreState } from '@app/core/services/store/index';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})

export class LoginComponent implements OnInit {
  validateForm!: FormGroup;
  actionCode = ActionCode;

  //count$: Observable<number>;
  count$: Observable<number>;;

  constructor(
    private fb: FormBuilder,
    private loginHttpService: LoginHttpService,
    private userService: UserService,
    private loginInOut: LoginInOutService,
    private router: Router,
    private store: Store<StoreState>,
    private testSelectors: TestSelectors,

  ) {
    this.count$ = this.testSelectors.count;
  }

  increment5(num: number) {
    this.store.dispatch(increment5({ count: num }));
  }

  increment() {
    this.store.dispatch(increment());
  }

  decrement() {
    this.store.dispatch(decrement());
  }

  reset() {
    this.store.dispatch(reset());
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsPristine();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }



  submitForm(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      this.loginHttpService.login(this.validateForm.value).subscribe(
        (res: NzSafeAny) => {
          console.log('subscribe', res);
          if (res.code === 2000) {
            //设置用户信息
            this.userService.setUserInfo(res.data.userInfo);
            //设置用户权限
            this.loginInOut.login(res.data.token);
            //跳转到
            this.router.navigateByUrl('/main');
          } else {
            console.log('error');
          }
        }
      );
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(12),
        forbiddenNameValidator(/bob/i)
      ]],
      password: [null, [Validators.required]],
      remember: [true]
    });

    if (window.electronAPI) {
      window.electronAPI.send('electronRenderToMain', { url: 'hello', action: 'getData', data: 'test' });
      window.electronAPI.receive('electronMaintoRender', (event, data) => {
        console.log('callback', data);
        if (data.to === 'login.component') {
          console.logR('callback', event, data);
        }
      });
      this.getTestData();
    }
  }

  async getTestData() {
    const data = await window.electronAPI.electronAjax({
      url: 'hello',
      action: 'ajaxData',
      data: 'ajaxData'
    })
    console.log('electronAjax', data);
  }

  gotoHome() {
    this.router.navigateByUrl('/home');
  }

  gotoMain() {
    this.router.navigateByUrl('/main');
  }

  gotoLogin() {
    this.router.navigateByUrl('/login');
  }

  mockLoginIn() {
    this.loginInOut.login('admin');
  }

  mockLogOut() {
    this.loginInOut.logout();
  }

}
